package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.DishMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional//开启事务
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;

    /**
     * c端登录
     *
     * @param dto
     * @return
     */
    @Override
    public Result login(UserLoginDTO dto) {
        //调用微信登录凭证校验接口
        //封装请求参数
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");

        String URL = "https://api.weixin.qq.com/sns/jscode2session";

        //调用接口 //用HttpClientUtil封装了方法,模拟浏览器发送一个get请求,参数时请求路径,和请求参数
        String body = HttpClientUtil.doGet(URL, paramMap);

        //解析body字符串,转换成Map获取openId
        Map map = JSON.parseObject(body, Map.class);
        if (map == null || map.size() == 0) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        String openid = (String) map.get("openid");
        log.info("微信用户返回的openid为:{}", openid);
        //判断openid是否为空
        if (openid == null) {
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否是新用户,如果是则注册
        //根据openid查询uer表
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            //没有数据是新用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }
        //封装数据返回
        String token = JwtUtil.getToken(user.getId());
        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(openid)
                .build();
        return Result.success(vo);
    }
}
